package com.fa.model
{
	import flash.display.Sprite;
	
	public class Snake extends Sprite
	{
		private static const INIT_SNAKE_LENGTH:int = 5;
		private static const INIT_SANKE_POSITION_X:int = 5;
		private static const INIT_SANKE_POSITION_Y:int = 5;
		private static const INIT_SANKE_DIRECTION:int = SnakeSegment.RIGHT;
		
		private var head:SnakeSegment = null;
		private var tail:SnakeSegment = null;
		
		public function Snake()
		{
			initSnake();
		}
		
		private function initSnake():void
		{
			var p:SnakeSegment = null;
			for(var i:int = 0; i < INIT_SNAKE_LENGTH; i++)
			{
				if(head == null)
				{
					head = constructNewSeg(INIT_SANKE_POSITION_X, INIT_SANKE_POSITION_Y, SnakeSegment.RIGHT);
					head.nextSeg = null;
					p = head;
				}
				else 
				{
					var bodySeg:SnakeSegment = constructNewSeg(INIT_SANKE_POSITION_X - i, INIT_SANKE_POSITION_Y, INIT_SANKE_DIRECTION);
					bodySeg.setDirection(INIT_SANKE_DIRECTION);
					bodySeg.nextSeg = p;
					p = bodySeg;
				}
				addChild(p);
			}
			tail = p;
		}
		
		private function constructNewSeg(col:int, row:int, dir:int):SnakeSegment
		{
			var seg:SnakeSegment = new SnakeSegment();
			seg.setCol(col);
			seg.setRow(row);
			seg.updatePosition();
			seg.setDirection(dir);
			return seg;
		}
		
		public function move():void
		{
			head.nextSeg = tail;
			tail = tail.nextSeg;

			var dx:int = 0;
			var dy:int = 0;
			switch(head.getDirection())
			{
			case SnakeSegment.LEFT:
				dx = -1;
				break;
			case SnakeSegment.UP:
				dy = -1;
				break;
			case SnakeSegment.RIGHT:
				dx = 1;
				break;
			case SnakeSegment.DOWN:
				dy = 1;
				break;
			}
			
			head.nextSeg.setDirection(head.getDirection());
			head.nextSeg.setCol(head.getCol() + dx);
			head.nextSeg.setRow(head.getRow() + dy);
			head.nextSeg.updatePosition();
			
			head = head.nextSeg;
			head.nextSeg = null;
		}
		
		public function turn(dir:int):void
		{
			head.setDirection(dir);
		}
		
		public function addBody():void
		{
			var newTail:SnakeSegment = new SnakeSegment();
			
			var dx:int = 0;
			var dy:int = 0;
			switch(tail.getDirection())
			{
				case SnakeSegment.LEFT:
					dx = 1;
					break;
				case SnakeSegment.UP:
					dy = 1;
					break;
				case SnakeSegment.RIGHT:
					dx = -1;
					break;
				case SnakeSegment.DOWN:
					dy = -1;
					break;
			}
			
			newTail.setDirection(tail.getDirection());
			newTail.setCol(tail.getCol() + dx);
			newTail.setRow(tail.getRow() + dy);
			newTail.updatePosition();
			addChild(newTail);
			newTail.nextSeg = tail;
			tail = newTail;
		}
		
		public function eat(food:Food):Boolean
		{
			if((food.getRow() == head.getRow()) && (food.getCol() == head.getCol()))
			{
				this.addBody();
				return true;
			}
			return false;
		}
	}
}